from app.models import ValueSetInterface, DataSet
from google.appengine.ext import db
import csv
import StringIO
import web

def query_all(job):
  dataset = DataSet.get(job.dataset_key)
  user = job.user
  interface = ValueSetInterface(user, dataset)
  
  virtual_csv_file = StringIO.StringIO()
  writer = csv.writer(virtual_csv_file, lineterminator='\n')
  writer.writerow(get_fields(job))
  
  q = interface.query(job.include_fieldset_keys, getattr(job, 'tags', []),
    job.filter_fieldset_keys)
  
  for valuesets in q:
    writer.writerow(get_values(valuesets))
  
  web.header('Content-type', 'application/octet-stream')
  web.header('Content-Disposition', 'attachment; filename=data.csv')
  return virtual_csv_file

def get_fields(job):
  headers = []
  for fieldset in db.get(job.include_fieldset_keys):
    for field in fieldset.fields_list:
      headers.append(field.verbose_name)  
  return headers

def get_values(valuesets):
  values = []
  for valueset in valuesets:
    if valueset: # This is incorrect behavior, should fix later
      values += valueset.to_list()
  return values
